//
//  SZYWCDBManager.m
//  WCDBDemo
//
//  Created by jiangdong on 2018/4/2.
//  Copyright © 2018年 jiangdong. All rights reserved.
//

#import "SZYWCDBManager.h"
#import "SZYMessage+WCTTableCoding.h"
#import "SZYMessage.h"
#import "SZYDetailScore.h"

@interface SZYWCDBManager()
{
    WCTDatabase *_database;
}

@property (nonatomic, copy) NSString *baseDirectory;

@end

#define SZY_TABLE_MESSAGE_NAME NSStringFromClass(SZYMessage.class)

@implementation SZYWCDBManager

+ (instancetype)shareInstance {
    static SZYWCDBManager * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SZYWCDBManager alloc] init];
        [instance creatDatabaseAndTable];
    });
    return instance;
}


// 创建数据库和表
- (BOOL)creatDatabaseAndTable {
    //数据库路径
    NSString *path = [self.baseDirectory stringByAppendingPathComponent:@"SampleDB"];
    NSLog(@"path--> %@",path);
    //创建数据库 路径一样,  该接口使用的是IF NOT EXISTS的SQL，因此可以用重复调用
    WCTDatabase *database = [[WCTDatabase alloc] initWithPath:path];
    _database = database;
    if (![database canOpen]) {
        NSLog(@"创建数据库失败");
        return NO;
    }
    if ([database isOpened]) {
        NSLog(@"数据库打开");
    }else{
        NSLog(@"创建数据库失败");
        return NO;
    }
    //清空数据库所有数据
//    [database close:^{
//        [database removeFilesWithError:nil];
//    }];
    
    //创建表  注：该接口使用的是IF NOT EXISTS的SQL，因此可以用重复调用。不需要在每次调用前判断表或索引是否已经存在。
    BOOL result = [database createTableAndIndexesOfName:SZY_TABLE_MESSAGE_NAME withClass:SZYMessage.class];

    if (!result) {
        NSLog(@"创建表失败");
        return NO;
    }
    return YES;
}

//插入单个数据
- (BOOL)insertData:(SZYMessage *)message {
    BOOL result = [_database insertObject:message into:SZY_TABLE_MESSAGE_NAME];
    
    //关闭数据库,_database如果能自己释放的话,会自动关闭,就不用手动调用关闭了
    [_database close];

    if (!result) {
        NSLog(@"插入失败");
        return NO;
    }else{
        NSLog(@"插入成功");
        return YES;
    }
}


//插入多个数据
- (BOOL)insertDatas:(NSArray<SZYMessage *> *)messages {
    //插入数据
    BOOL result = [_database insertObjects:messages into:SZY_TABLE_MESSAGE_NAME];
    [_database close];

    if (!result) {
        NSLog(@"Insert objects Error ");
        return NO;
    }else{
        NSLog(@"插入数据成功");
        return YES;
    }
    
    //下面写法可以链式调用
    //    WCTInsert *insert = [_database prepareInsertObjectsOfClass:SZYMessage.class
    //                                                          into:SZY_TABLE_MESSAGE_NAME];
    //    BOOL result = [insert executeWithObjects:objects];
}



//查询
- (void)selectData {
    
    [self selectOrder];
    
//    [self selectCertainRange];
    
//    [self selectCertainRange2];
    
//    [self selectAndAssignment];
    
//    [self selectChain];
    [_database close];

}


//查询数据  用localID排序
- (void)selectOrder {
    NSArray<SZYMessage *> *objects2 = [_database getObjectsOfClass:SZYMessage.class fromTable:SZY_TABLE_MESSAGE_NAME orderBy:SZYMessage.localID.order()];
    [objects2 enumerateObjectsUsingBlock:^(SZYMessage *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSLog(@"用localID排序 --> %@ %f  %f ",obj,obj.detailScore.math,obj.detailScore.english);
    }];
}

//查询数据  指定范围
- (void)selectCertainRange {
    NSArray<SZYMessage *> *objects3 = [_database getObjectsOfClass:SZYMessage.class fromTable:SZY_TABLE_MESSAGE_NAME where:SZYMessage.localID.between(0,1) || SZYMessage.name.like(@"lil%")];
    [objects3 enumerateObjectsUsingBlock:^(SZYMessage *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"objects3 --> %@ ",obj);
    }];
}

- (void)selectCertainRange2 {
    NSArray<SZYMessage *> *objects4 = [_database getObjectsOfClass:SZYMessage.class fromTable:SZY_TABLE_MESSAGE_NAME where:SZYMessage.isPass && SZYMessage.totalScore > 50];
    [objects4 enumerateObjectsUsingBlock:^(SZYMessage *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"objects4 --> %@ ",obj);
    }];
}

//定向 将查询的totalScore值赋给新创建的对象
- (void)selectAndAssignment {
    SZYMessage *message5 = [_database getOneObjectOnResults:SZYMessage.totalScore.max().as(SZYMessage.totalScore) fromTable:SZY_TABLE_MESSAGE_NAME];
    message5.localID = 5;
    NSLog(@"message5 --> %@ ",message5);
}

//链式调用
- (void)selectChain {
/*
    WCTInsert
     WCTDelete
     WCTUpdate
     WCTSelect
 */
    //所有的对象
    WCTSelect *select = [_database prepareSelectObjectsOfClass:SZYMessage.class fromTable:SZY_TABLE_MESSAGE_NAME ];
    NSArray *objects = select.allObjects;

    //链式查询
    NSArray<SZYMessage *> *objects6 = [[select where:SZYMessage.totalScore < 90] limit:2].allObjects;
    [objects6 enumerateObjectsUsingBlock:^(SZYMessage *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"objects6 --> %@ ",obj);
    }];
}



//更新
- (void)updateData {
    WCTUpdate *update = [_database prepareUpdateTable:SZY_TABLE_MESSAGE_NAME
                                        onProperties:SZYMessage.name];
    SZYMessage *object = [[SZYMessage alloc] init];
    object.name = @"xiaoming22";
    BOOL result = [update executeWithObject:object];
    if (!result) {
        NSLog(@"Update by object Error %@", update.error);
    }else{
        NSLog(@"更新成功");
    }
    
}

//删除表
- (void)deleteData {
    WCTDelete *deletion = [_database prepareDeleteFromTable:SZY_TABLE_MESSAGE_NAME];
    BOOL result = [deletion execute];
    if (!result) {
        NSLog(@"Delete Error %@", deletion.error);
    }else{
        NSLog(@"删除成功");
    }

    [_database close];
    //删除name是xiaoming的人
//    BOOL result = [_database deleteObjectsFromTable:SZY_TABLE_MESSAGE_NAME where:SZYMessage.name == @"xiaoming"];
//    [_database deleteObjectsFromTable:SZY_TABLE_MESSAGE_NAME where:SZYMessage.localID.between(0,1) || SZYMessage.name.like(@"lil%")];
    
}

//事务
- (void)transactionUseBlock {
//    blocked 方式用事务
    BOOL committed = [_database runTransaction:^BOOL{
        SZYMessage *object = [[SZYMessage alloc] init];

        BOOL result = [_database insertObject:object
                                     into:SZY_TABLE_MESSAGE_NAME];
        //return YES to do a commit and return NO to do a rollback
        if (result) {
            return YES;
        }
        return NO;
    } event:^(WCTTransactionEvent event) {
        NSLog(@"Event %d", event);
    }];
    
}

//不用block方式事务
- (void)transaction {
    BOOL result = [_database beginTransaction];
    SZYMessage *object = [[SZYMessage alloc] init];
    result = [_database insertObject:object
                            into:SZY_TABLE_MESSAGE_NAME];
    if (result) {
        result = [_database commitTransaction];
    } else {
        result = [_database rollbackTransaction];
    }
}


- (NSString *)baseDirectory {
    if (_baseDirectory == nil) {
        _baseDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    }
    return  _baseDirectory;
}

@end
